package com.why.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.InputStream;
public class AliOssUtil {
    public static String uploadFile(String objectName, InputStream in) throws Exception {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 从环境变量中获取访问凭证。确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称。
        String bucketName = "why-big-event";

        // 填写Bucket所在地域。
        String region = "cn-beijing";

        // 创建OSSClient实例。
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        String url = "";
        try {
            // 创建一个PutObjectRequest对象，使用传入的objectName和InputStream。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, in);

            // 上传文件。
            ossClient.putObject(putObjectRequest);

            // 构建文件的URL。
            url = "https://" + bucketName + "." + endpoint.substring(endpoint.lastIndexOf("/") + 1) + "/" + objectName;

        } catch (OSSException oe) {
            System.out.println("OSSException: " + oe.getErrorMessage());
            // 可以选择抛出异常或者记录日志等
        } catch (ClientException ce) {
            System.out.println("ClientException: " + ce.getMessage());
            // 可以选择抛出异常或者记录日志等
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
